package preferorg

import (
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/balancer"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/common/logging"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/events/client/inoderesolver"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/context"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
)

var logger = logging.NewLogger("ichainsdk/ichain")

// InodeResolver  相同组织策略
type InodeResolver struct {
	balance balancer.Balancer
	iamID   string
}

func NewResolver() inoderesolver.Provider {
	return func(context context.Client, chainID string) inoderesolver.Resolver {
		return New(context, chainID)
	}
}

func New(context context.Client, chainID string) *InodeResolver {
	balance := balancer.GetBalancer(context.EndpointConfig().ChainConfig(chainID).Policies.EventService)
	iamID := context.Identifier().IAMID

	logger.Debugf("Creating new PreferOrg inode resolver with options: IAM ID [%s]", iamID)

	return &InodeResolver{
		iamID:   iamID,
		balance: balance,
	}
}

func (r *InodeResolver) Resolve(inodes []ichain.Inode) (ichain.Inode, error) {
	var orgInodes []ichain.Inode
	for _, p := range inodes {
		if p.IAMID() == r.iamID {
			orgInodes = append(orgInodes, p)
		}
	}

	// 先按照区块高度策略过滤一次
	if len(orgInodes) > 0 {
		logger.Debugf("Choosing a inode from [%s]", r.iamID)
		return r.balance.Choose(orgInodes)
	}

	logger.Debugf("Choosing a inode from another org since there are no inodes from [%s] in the list of inodes", r.iamID)
	return r.balance.Choose(inodes)
}
